<?php
/**
 * This file is form http://findcat.cn
 *
 * @link     https://findcat.cn
 * @email    1476982312@qq.com
 */
namespace App\Http\Controllers\Auth;

use App\Models\User;
use App\Models\UserOath;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Overtrue\LaravelSocialite\Socialite;

class SocialiteLoginController extends Controller
{
    /**
     * @var UserOath
     */
    protected $oath;

    /**
     * @var User
     */
    protected $user;

    /**
     * SocialiteLoginController constructor.
     */
    public function __construct(UserOath $oath, User $user)
    {
        $this->oath = $oath;
        $this->user = $user;
    }

    /**
     * @return mixed
     */
    public function redirectToProvider()
    {
        return Socialite::driver('qq')->redirect();
    }

    public function handleProviderCallback()
    {
        $oauthUser = Socialite::driver('qq')->user();

        $oath = $this->oath->where('token', $oauthUser->token)->whereHas('user')->first();

        if (!$oath) {
            $user = User::query()->create([
                'name'  => $oauthUser->name ?? $oauthUser->nickname,
                'email' => $oauthUser->email ?? '',
            ]);

            UserOath::query()->create([
                'user_id'  => $user->id,
                'unionid'  => $oauthUser->unionid,
                'nickname' => $oauthUser->nickname,
                'name'     => $oauthUser->name,
                'email'    => $oauthUser->email,
                'avatar'   => $oauthUser->avatar,
                'original' => $oauthUser->original,
                'token'    => $oauthUser->token,
                'provider' => $oauthUser->provider,
            ]);
        } else {
            $user = $oath->user;
        }

        Auth::guard('web')->loginUsingId($user->id);

        return redirect('/');
    }
}
